<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-10-25
 * @Time: 10:10
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： News.php
 */
namespace app\api\model;

use think\Db;
use think\Model;

class News extends Model {
    /**
     * query_news
     * 根据条件查询获取资讯数据
     *
     * @author zhengkai
     * @date 2017-10-25
     * @version V1.1
     *
     * @return \think\response\Json
     * TODO 相关查询条件数组库、管理功能等还未创建
     */
    public function query_news()
    {
        $data = Db::table('teacher_essay')->alias('news')
            ->join('teacher t', 'news.teacher_id=t.id', 'LEFT')
            ->where('news.category', 3)
            ->where('news.hide', 'false')
            ->field('
            news.id as news_id,
            news.title as news_title,
            news.summary as news_summary,
            news.created as news_time,
            t.id as teacher_id,
            t.name as teacher_name,
            t.avatar as teacher_avatar
            ')
            ->order('news.id desc')
            ->select();

        $arr = [];
        foreach ($data as $key=>$val) {
            $val['news_time'] = tranTime(strtotime($val['news_time']));

            $arr[] = $val;
        }
        $result = $arr;

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * get_news
     * 获取手动推荐资讯和最新资讯数据
     *
     * @author zhengkai
     * @date 2017-11-02
     * @version v1.1
     *
     * @param int $isRc 是否加载推荐文章
     * @param int $num 加载数据条数，默认5
     * @return \think\response\Json
     */
    public function get_news($isRc=1, $num=5)
    {
        // 手动推荐资讯
        $recData = Db::query("select te.id as news_id, te.title as news_title, te.summary as news_summary, te.cover as news_cover, t.realname as teacher_name, te.created as news_time from teacher_essay as te
left join teacher t on te.teacher_id = t.id
where te.recommend='true'
order by te.created desc limit 1");
        $recArr = [];
        foreach ($recData as $key=>$val) {
            $time = $val['news_time'];
            $val['news_time'] = tranTime(strtotime($time));

            $recArr[] = $val;
        }

        // 最新资讯
        $sql = <<<SQL
select te.id as news_id, te.title as news_title, t.realname as teacher_name, te.created as news_time from teacher_essay as te
left join teacher t on te.teacher_id = t.id
order by te.created desc limit {$num}
SQL;
        $data = Db::query($sql);

        $arr = [];
        foreach ($data as $key=>$val) {
            $time = $val['news_time'];
            $val['news_time'] = date('Y/m/d', strtotime($time));

            $arr[] = $val;
        }
        $result = [
            'rec' => $recArr?$recArr[0]:(object)[],
            'news' => $arr
        ];

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));


    }
}